﻿using Lawn.NetMessager;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinMessageRec
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            clientReceiver  = new MessageReciver(txtUrl.Text.Trim(), int.Parse(txtPort.Text.Trim()),new string[] { "reply_top1", "reply_top2", "reply_top3" });

            clientReceiver.ConnectError += ClientReceiver_ConnectError;
            clientReceiver.Connected += ClientReceiver_Connected;
            clientReceiver.MessageRecive += ClientReceiver_MessageRecive;
            this.FormClosing += Form1_FormClosing;
        }


        private void SetText(Control ct,string val)
        {


            if ( this.IsDisposed) return;
             
                if (ct.InvokeRequired)
                {
                    ct.BeginInvoke(new Action<Control, string>(SetText), new object[] { ct, val });
                }
                else
                {
                    ct.Text = val;
                } 
           
        }

        private void ClientReceiver_MessageRecive(object sender, MessageEventArgs e)
        {

            SetText(textBox1, $"{e.Topic}--{Encoding.UTF8.GetString(e.Data)}");
           

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            clientReceiver.Stop();
        }

        private void ClientReceiver_Connected(object sender, EventArgs e)
        {
            SetText(txtStatus, $"Connected");
           // this.txtStatus.Text = $"Connected+{clientReceiver.HeatData.Count}";
        }

        private void ClientReceiver_ConnectError(object sender, EventArgs e)
        {
            SetText(txtStatus, "Error");
           
          //  this.txtStatus.Text = "Error";
        }

        private MessageReciver clientReceiver = null;

        private void button1_Click(object sender, EventArgs e)
        {


            clientReceiver.Start();


        }
    }
}
